// 智能合约 比金额大小游戏
import Web3 from "web3";
import {Button, Card,  Divider, Input, Space, Tag,  InputNumber} from "antd";
import React from "react";
import {FailedNotice, SuccessNotice} from "../../components/Notice";

let web3;
let abi =[
    {
        "inputs": [],
        "stateMutability": "nonpayable",
        "type": "constructor"
    },
    {
        "inputs": [],
        "name": "getGod",
        "outputs": [
            {
                "internalType": "address",
                "name": "",
                "type": "address"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "getPlayers",
        "outputs": [
            {
                "internalType": "address",
                "name": "",
                "type": "address"
            },
            {
                "internalType": "address",
                "name": "",
                "type": "address"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "offer",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            },
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            },
            {
                "internalType": "address",
                "name": "",
                "type": "address"
            }
        ],
        "stateMutability": "payable",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "queryBalance",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    }
];
let contractAddress = "0x5A5d699F95693fb0A6e427540880538c80D9605b";
let contract;

export default ContrastValue;

function ContrastValue() {
    initWeb3()

    const [God, setGod] = React.useState("")

    contract.methods.getGod().call().then(function (v) {
        setGod(v);
    })

    return (
        <>
            God : <Tag color={"red"}>{God}</Tag>
            <Divider/>

            <GameRole/>

            <Auth/>

            <PlaceChip/>

            <ShowBalance/>

        </>
    )
}


function initWeb3() {

    if(window.ethereum){
        web3 = new Web3(window.ethereum)
    }else{
        FailedNotice("请先安装MetaMask")
        return;
    }

    contract = new web3.eth.Contract(abi, contractAddress)

    metaMaskAuth()
}

// 一、游戏规则
function GameRole() {
    return (
        <>
            <Card title="一、游戏规则">
                <ul>
                    <li>玩家数：2</li>
                    <li>筹码：余额</li>
                    <li>双方玩家压上一定的筹码，赢者通吃</li>
                    <li>筹码相等，先家赢</li>
                </ul>
            </Card>
            <br/>
        </>
    )
}

// 二、授权
function Auth() {

    return (
        <>
            <Card title="二、授权">
                <Button type="primary" onClick={metaMaskAuth}>钱包授权</Button>
                &nbsp;
                <Button type="info" onClick={queryCurrentAccount}>查看当前授权地址</Button>
            </Card>
            <br/>
        </>
    )
}

// 三、开始游戏
function PlaceChip() {

    const [playerA,setPlayerA] = React.useState("暂无玩家，您可先入场")
    const [value,setValue] = React.useState(0)

    reFreshPlayers(setValue);

    return (
        <>
            <Card title="三、放置筹码">
                <div>当前玩家：<Tag color={"blue"}>{playerA}</Tag></div><br/>

                <InputNumber min={1} value={value} onChange={setValue}/> （单位：wei）
                <br/>
                <Button type="primary" onClick={()=>{offer(value,setPlayerA)}}> 下注 </Button>
            </Card>
            <br/>
        </>
    )
}

// 用于检查余额
function ShowBalance() {

    const [balance, setBalance] = React.useState(0)

    return (
        <Space>
            <Input value={balance}/>
            <Button type="primary" onClick={() => {

                if (!isAuth()) {
                    FailedNotice("请先授权", 3)
                    return
                }

                queryGameBalance().then(function (v) {
                    console.log("queryGameBalance",v)
                    setBalance(v)
                }).catch(function (e) {
                    console.log(e)
                    FailedNotice(e.toString())
                })

            }}> 获取当前余额 </Button>
        </Space>
    )
}



// 查看当前的默认地址
function queryCurrentAccount() {

    let account = web3.eth.defaultAccount;
    if (account == null) {
        FailedNotice("当前默认地址为空", 1)
        return
    }

    SuccessNotice(account, 1)
}

// 查看当前游戏的余额
function queryGameBalance() {
    return new Promise(function (resolve, reject) {
        contract.methods.queryBalance().call({from: web3.eth.defaultAccount}).then(function (v) {
            resolve(v)
        }).catch(function (err) {
            reject(err)
        })
    })

}

function isAuth() {
    return web3.eth.defaultAccount !== null;
}

function reFreshPlayers(setFunc){
    requestGetPlayers().then(function (res) {

        if(res.length < 1){
            FailedNotice("获取玩家失败，请不要下注")
            return
        }

        // 拿到玩家一即可
        if(res[0] !== "0x0000000000000000000000000000000000000000"){
            setFunc(res[0])
        }

        console.log("reFreshPlayers",res)
    })
}

function offer(money,setPlayerA){
    if (money < 1){
        FailedNotice("压注必须大于0");
        return;
    }

    contract.methods.offer().send({from:web3.eth.defaultAccount,value:money}).then(function (res) {

        console.log("offer()",res)

        // 刷新当前玩家的名称
        reFreshPlayers(setPlayerA)

    }).catch(function (e){
        console.log("offer() catch",e)
    })
}



// API

// 请求获取当前玩家列表
function requestGetPlayers(){
    return new Promise(function(resoleve,reject){
        contract.methods.getPlayers().call().then(function (result){
            resoleve(result)
        }).catch(function (e) {
            reject(e)
        })
    })
}

// 小狐狸metamask钱包授权
function metaMaskAuth() {
    window.ethereum.enable().then(function (accounts) {
        web3.eth.defaultAccount = accounts[0]
        console.log("Metamask 授权成功");
    }).catch(function (err) {
        console.log(err)
        FailedNotice(err.message, 1)
    })
}